package com.xd.clap.utils;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xd.clap.entity.GridOperator;
import com.xd.clap.entity.response.AddGridOperator;
import com.xd.clap.services.GridOperatorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@Transactional
public class ExcelUtil {

    @Autowired
    private GridOperatorService gridOperatorService;

    private static com.xd.clap.utils.ExcelUtil excelUtil;

    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        excelUtil = this;
        excelUtil.gridOperatorService = this.gridOperatorService;
    }

    /**
     * 读取excel数据，并存入数据库
     * @param file
     * @throws IOException
     */
    public static void importData(MultipartFile file) throws IOException {
        // 构建 ExcelReader 对象，从第二行开始
        ExcelReader excelReader = EasyExcel.read(file.getInputStream(), AddGridOperator.class, new GridListener()).headRowNumber(1).build();
        // 读取 Excel 表格中的数据
        excelReader.readAll();
        // 关闭 ExcelReader
        excelReader.finish();
    }

    private static class GridListener extends AnalysisEventListener<AddGridOperator> {
        // 批量处理的数据大小
        private static final int BATCH_COUNT = 5;
        // 数据集合
        private List<GridOperator> list = new ArrayList<>();
        // 每读取一行数据就会调用该方法
        @Override
        public void invoke(AddGridOperator addGridOperator, AnalysisContext analysisContext) {
            System.out.println(addGridOperator);
            // 将读取到的数据添加到数据集合中
            GridOperator gridOperator = new GridOperator();
            gridOperator.setGridName(addGridOperator.getGridName());
            gridOperator.setPhonenum(addGridOperator.getPhonenum());
            gridOperator.setBelongs(addGridOperator.getBelongs());
            gridOperator.setGridDuties(addGridOperator.getGridDuties());
            list.add(gridOperator);
            // 每 BATCH_COUNT 条数据，就将数据存入数据库中，并清空数据集合
            if (list.size() >= BATCH_COUNT) {
                saveData();
                list.clear();
            }
        }
        // 读取完整个 Excel 表格后就会调用该方法
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            saveData();
            log.info("所有数据解析完成！");
        }
        // 将数据存入数据库中
        public void saveData() {
            log.info("{}条数据，开始存储数据库！", list.size());
            //插入数据，相同手机号数据覆盖、数据库没有的手机号添加数据
            for(GridOperator gridOperator :list){
                QueryWrapper<GridOperator> wrapper = new QueryWrapper<GridOperator>()
                        .select("grid_id","grid_name")
                        .eq("phonenum", gridOperator.getPhonenum());
                GridOperator grid= excelUtil.gridOperatorService.getOne(wrapper);
                if(grid != null){
                    gridOperator.setGridId(grid.getGridId());
                    excelUtil.gridOperatorService.updateGrid(gridOperator);
                }else {
                    excelUtil.gridOperatorService.addGrid(gridOperator);
                }
            }

        }
    }
}
